<script setup lang="ts">
import Sidebar from "./components/Sidebar.vue";
import ChatInput from "./components/ChatInput.vue";
import ChatMessages from "./components/ChatMessages.vue";
import SystemPrompt from "./components/SystemPrompt.vue";
import ModelSelector from "./components/ModelSelector.vue";
import {
  currentModel,
  isDarkMode,
  isSettingsOpen,
  isSystemPromptOpen
} from "@/views/domain/knowledge/config/ollama";
import { onMounted, ref } from "vue";
import { useAI } from "@/views/domain/knowledge/store/useAI";
import { useChats } from "@/views/domain/knowledge/store/chat";
import TextInput from "./components/Inputs/TextInput.vue";
import Settings from "./components/Settings.vue";

const { refreshModels, availableModels } = useAI();
const { activeChat, renameChat, switchModel, initialize, hasMessages } =
  useChats();
const isEditingChatName = ref(false);
const editedChatName = ref("");

const startEditing = () => {
  isEditingChatName.value = true;
  editedChatName.value = activeChat.value?.name || "";
};

const cancelEditing = () => {
  isEditingChatName.value = false;
  editedChatName.value = "";
};

const confirmRename = () => {
  if (activeChat.value && editedChatName.value) {
    renameChat(editedChatName.value);
    isEditingChatName.value = false;
  }
};

onMounted(() => {
  refreshModels().then(async () => {
    await initialize();
    await switchModel(currentModel.value ?? availableModels.value[0].name);
  });
});
</script>
<template>
  <div class="chat-scaffold">
    <div class="chat-list">
      <Sidebar />
    </div>

    <el-container class="chat-container">
      <el-header class="head">
        <el-input
          v-if="isEditingChatName"
          v-model:model-value="editedChatName"
          @keyup.enter="confirmRename"
          @keyup.esc="cancelEditing"
        />
        <div v-else @click="startEditing">
          <el-text>{{ activeChat?.name }}</el-text>
        </div>

        <ModelSelector :disabled="hasMessages" />
      </el-header>
      <el-main class="chat-body">
        <ChatMessages />
      </el-main>
      <el-footer class="chat-input">
        <ChatInput />
      </el-footer>
    </el-container>
  </div>
</template>
<style lang="scss" scoped>
.chat-scaffold {
  display: flex;
  height: 100%;
}

.chat-list {
  width: 200px;
  height: 100%;
}

.chat-container {
  flex: 1;
  display: inline-flex;
  flex-direction: column;

  .head {
    height: 50px;
    display: flex;
    align-items: center;
    justify-content: space-between;
    border-bottom: 1px solid #e5e5e5;

    .chat-title {
      display: flex;
      justify-content: space-between;
    }
  }

  .chat-body {
    padding: 5px 0;
  }
  .chat-input {
    width: 100%;
    padding: 10px;
    height: 100px;
  }
}
</style>
